<template>
	<picker :value="currentIndex" :range="data.options" range-key="text" @change="change">
		<view class="flex align-center">
			<view class="h-30 w-100 text-14 flex align-center justify-end" v-if="!isEmpty(currentIndex)">{{ data.options[currentIndex]?.text }}</view>
			<view class="h-30 w-100 text-14 flex align-center justify-end gray9" v-else>{{ data.placeholder }}</view>
			<uni-icons :size="16" color="#bbb" type="arrowright" />
		</view>
	</picker>
</template>

<script setup lang="ts">
import { watch, ref } from 'vue'
import { isEmpty } from '@/assets/js/utils'

const currentIndex = ref()
const props = defineProps({
	//表单组件参数
	data: {
		type: Object,
		required: true
	},
	modelValue: {}
})

watch(props, (val: any) => {
	initIndex()
})

//因picker组件回显值只能使用index下标，故根据回显值初始化相应下标
const initIndex = () => {
	let index: any
	if (props.data.options && props.modelValue) {
		index = props.data.options.findIndex((item: any) => {
			return item.value == props.modelValue
		})
	}
	if (isEmpty(props.modelValue)) index = undefined
	currentIndex.value = index
}

if (props.modelValue && props.data.options) initIndex()

//修改双向绑定值
const emit = defineEmits(['update:modelValue', 'valueChange'])
const change = e => {
	currentIndex.value = e.detail.value
	let value = props.data.options[e.detail.value].value
	emit('update:modelValue', value)
	emit('valueChange', value)
}
</script>
